<template>
  <div class="user-profile">
    <div class="avatar-section">
      <div class="avatar-container">
        <img
          :src="avatarUrl || '/default-avatar.png'"
          alt="用户头像"
          class="avatar"
        />
        <div class="avatar-overlay" @click="triggerFileInput">
          <span>更换头像</span>
        </div>
      </div>
      <input
        type="file"
        ref="avatarInput"
        @change="handleAvatarUpload"
        accept="image/*"
        style="display: none"
      />
    </div>
    <h1>用户个人资料</h1>
    <form @submit.prevent="updateProfile">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div class="form-group">
        <label for="email">邮箱</label>
        <input type="email" id="email" v-model="email" required />
      </div>
      <button type="submit">更新资料</button>
    </form>
    <button @click="logout" class="logout-button">退出</button>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import {
  fetchUserProfile,
  updateUserProfile,
  uploadUserAvatar
} from '../services/api';
import { useUserStore } from '../stores/userStore';

const username = ref('');
const email = ref('');
const avatarUrl = ref('');
const avatarInput = ref(null);
const router = useRouter();
const store = useUserStore();

// 获取用户信息
const getUserProfile = async () => {
  try {
    const response = await fetchUserProfile();
    username.value = response.data.username;
    email.value = response.data.email;
    avatarUrl.value = response.data.avatar || '/default-avatar.png';
  } catch (error) {
    console.error('获取用户信息错误:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 触发文件输入
const triggerFileInput = () => {
  avatarInput.value.click();
};

// 处理头像上传
const handleAvatarUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型和大小
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  const maxSize = 5 * 1024 * 1024; // 5MB

  if (!validTypes.includes(file.type)) {
    ElMessage.error('请上传有效的图片格式（JPEG, PNG, GIF, WEBP）');
    return;
  }

  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过5MB');
    return;
  }

  try {
    // 创建FormData上传文件
    const formData = new FormData();
    formData.append('avatar', file);

    // 调用上传API
    const response = await uploadUserAvatar(formData);

    // 更新头像URL
    avatarUrl.value = response.data.avatarUrl;

    // 显示成功消息
    ElMessage.success('头像上传成功');
    // 刷新页面
    window.location.reload();
  } catch (error) {
    console.error('头像上传失败:', error);
    ElMessage.error('头像上传失败: ' + error.message);
  }
};

// 更新用户资料
const updateProfile = async () => {
  try {
    const userData = {
      username: username.value,
      email: email.value,
    };
    await updateUserProfile(userData);
    ElMessage.success('用户资料更新成功');
  } catch (error) {
    console.error('更新用户资料失败:', error);
    ElMessage.error('更新用户资料失败: ' + error.message);
  }
};

// 退出功能
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '退出', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token');
    store.setLoggedIn(false);
    router.push('/');
  }).catch(() => {
    // 取消退出
  });
};

// 在组件挂载时获取用户信息
onMounted(getUserProfile);
</script>

<style scoped>
.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-container {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  color: white;
  font-size: 14px;
}

.user-profile {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  background: transparent;
  color: #f3f4f6;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #111827;
  color: #f3f4f6;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #3450ff;
  outline: none;
}

button {
  width: 100%;
  padding: 10px;
  background: #3450ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: #2440db;
}

.logout-button {
  margin-top: 15px;
  background: #e53e3e;
}

.logout-button:hover {
  background: #c53030;
}
</style>
